package com.example.web;

import com.example.pojo.User;
import com.example.service.UserService;
import com.example.service.impl.UserServiceImpl;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;

@WebServlet(name = "RegisterServlet", value = "/RegisterServlet")
public class RegisterServlet extends HttpServlet {

    private UserService userService = new UserServiceImpl();

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //  1.获取请求参数
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String email = request.getParameter("email");
        String code = request.getParameter("code");
        //  2.检查验证码是否正确 === 先写死，为abcd
        if("abcd".equalsIgnoreCase(code)){
            //正确
            //3.检查用户名是否可用
            if (userService.existUsername(username)){
                //不可用
                System.out.println("用户名["+username+"]已存在");
                //把回显信息放入request域中
                request.setAttribute("msg", "用户名已存在！");
                request.setAttribute("username", username);
                request.setAttribute("email", email);
                //跳回注册页面    register.jsp
                request.getRequestDispatcher("/pages/user/register.jsp").forward(request, response);
            }else{
                //可用
                //调用Service保存到数据库
                userService.registerUser(new User(null, username, password, email));
                //跳到注册成功页面  register_success.jsp
                request.getRequestDispatcher("/pages/user/register_success.jsp").forward(request, response);
            }
        }else{
            //不正确
            System.out.println("验证码["+code+"]错误");
            //把回显信息放入request域中
            request.setAttribute("msg", "验证码错误！");
            request.setAttribute("username", username);
            request.setAttribute("email", email);
            //跳回注册页面    register.jsp
            request.getRequestDispatcher("/pages/user/register.jsp").forward(request, response);
        }
    }
}
